package com.ht.pms.core.controller.template;

import com.ht.pms.core.common.exception.ServiceException;
import com.ht.pms.core.dto.Result;
import com.ht.pms.core.dto.send.CountSendNumberDto;
import com.ht.pms.core.dto.send.SalaryAccessDto;
import com.ht.pms.core.dto.send.SendSalaryReq;
import com.ht.pms.core.service.DingDingService;
import com.ht.pms.core.service.SalaryEmailService;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sendinfo")
//@CrossOrigin
public class SalaryEmailController {
    private static final Logger LOG = LoggerFactory.getLogger(SalaryEmailController.class);


    @Autowired
    private SalaryEmailService salaryEmailService;

    @Autowired
    private DingDingService dingDingService;


    @PostMapping(value = "/sendSalaryEmail")
    @ResponseBody
    @ApiOperation("发送消息")
    public Result sendSalaryEmail(@RequestBody SendSalaryReq dto) throws Exception {
        LOG.info("=================>>>>发送消息接口开始");
        Result result = null;
        try {
            if (!StringUtils.isEmpty(dto.getEndDate())) {
                Date endDate = dto.getEndDate();
                String time = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(endDate);
                dto.setEndCheckTime(time);
            }
            List<Integer> serverIds = dto.getSendServer();
            if (!CollectionUtils.isEmpty(serverIds)) {
                if (serverIds.size() == 2) {
                    salaryEmailService.sendSalaryEmail(dto);
                    dingDingService.sendDingdingMsg(dto);
                } else if (serverIds.size() == 1) {
                    if (serverIds.get(0).equals(1)) { //发送邮件
                        salaryEmailService.sendSalaryEmail(dto);
                    } else if (serverIds.get(0).equals(2)) { //发送钉钉
                        dingDingService.sendDingdingMsg(dto);
                    }
                }
            }


            result = Result.buildSuccess();
        } catch (ServiceException se) {
            LOG.error("=============>>>>发送消息出错", se);
            result = Result.buildFail(se.getCodeDesc(), se.getErrorMsg());
        } catch (Exception e) {
            LOG.error("=============>>>>发送消息出错", e);
            result = Result.buildFail();
        }
        LOG.info("=================>>>>发送消息结束{}", result);
        return result;
    }


    @GetMapping(value = "/createSendSalaryData")
    @ResponseBody
    @ApiOperation("生成工资/考勤模板发送数据")
    public Result createSendSalaryData(String code) throws Exception {
        LOG.info("=================>>>>生成组合工资模板发送数据开始code=" + code);
        Result result = null;
        try {

            //工资模板
            Map<String, Object> sendMapData = salaryEmailService.createSendSalaryData(code);

            result = Result.buildSuccess(sendMapData);
        } catch (Exception e) {
            LOG.error("=============>>>>生成组合工资模板发送数据出错", e);
            result = Result.buildFail();
        }
        LOG.info("=================>>>>生成组合工资模板发送数据结束{}", result);
        return result;
    }

    /**
     *
     * @param jobCode
     * @param batchCode
     * @param sendType 1 考勤；2 薪资
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/createSendSalaryDataInner")
    @ResponseBody
    @ApiOperation("生成工资/考勤模板发送数据内部")
    public Result createSendSalaryDataInner(String jobCode, String batchCode, int sendType) throws Exception {
        LOG.info("=================>>>>生成内部工资/考勤发送开始");
        Result result = null;
        try {

            Map<String, Object> sendMapData = salaryEmailService.createSendSalaryDataInner(jobCode, batchCode, sendType);

            result = Result.buildSuccess(sendMapData);
        } catch (Exception e) {
            LOG.error("=============>>>>生成内部工资/考勤发送出错", e);
            result = Result.buildFail();
        }
        LOG.info("=================>>>>生成内部工资/考勤发送结束{}", result);
        return result;
    }


//    @PostMapping(value = "/accessSendEmail")
//    @ApiOperation("查看url是否可以访问")
//    public Result accessSendEmail(HttpServletRequest request, HttpServletResponse response, String code, String sendType) throws Exception {
//        LOG.info("=================>>>>查看url是否可以访问开始");
//        Result result = null;
//        try {
//
//            SalaryAccessDto salaryAccessDto = salaryEmailService.accessSendEmail(code, sendType);
//
//            result = Result.buildSuccess(salaryAccessDto);
//        } catch (Exception e) {
//            LOG.error("=============>>>>查看url是否可以访问出错", e);
//            result = Result.buildFail();
//        }
//        LOG.info("=================>>>>查看url是否可以访问结束{}", result);
//        return result;
//    }

    /**
     * 撤回
     *
     * @param request
     * @param response
     * @param type      1 批量  2 单个
     * @param jobCode
     * @param batchCode
     * @param sendType
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/sendRecall")
    @ApiOperation("撤回")
    public Result sendRecall(HttpServletRequest request, HttpServletResponse response, int type, String jobCode, String batchCode, int sendType, String sendServer) throws Exception {
        LOG.info("=================>>>>查看url是否可以访问开始");
        Result result = null;
        try {
            List<Integer> sendServerList=new ArrayList<>();
            if(!StringUtils.isEmpty(sendServer)){
              String[] arr=  sendServer.split(",");
              if(arr.length>1){
                  sendServerList.add(Integer.parseInt(arr[0]));
                  sendServerList.add(Integer.parseInt(arr[1]));
              }else {
                  sendServerList.add(Integer.parseInt(arr[0]));
              }

            }

            dingDingService.sendRecall(type, jobCode, batchCode, sendType, sendServerList);

            result = Result.buildSuccess();
        } catch (ServiceException se) {
            LOG.error("=============>>>>撤回出错", se);
            result = Result.buildFail(se.getCodeDesc(), se.getErrorMsg());
        } catch (Exception e) {
            LOG.error("=============>>>>查看url是否可以访问出错", e);
            result = Result.buildFail();
        }
        LOG.info("=================>>>>查看url是否可以访问结束{}", result);
        return result;
    }

    @GetMapping(value = "/countSendNumber")
    @ApiOperation("发送记录数统计")
    public Result countSendNumber(HttpServletRequest request, HttpServletResponse response, String batchCode) throws Exception {
        LOG.info("=================>>>>发送记录数统计开始");
        Result result = null;
        try {

            CountSendNumberDto countSendNumberDto = salaryEmailService.countSendNumber(batchCode);

            result = Result.buildSuccess(countSendNumberDto);
        } catch (ServiceException se) {
            LOG.error("=============>>>>发送记录数统计出错", se);
            result = Result.buildFail(se.getCodeDesc(), se.getErrorMsg());
        } catch (Exception e) {
            LOG.error("=============>>>>发送记录数统计出错", e);
            result = Result.buildFail();
        }
        LOG.info("=================>>>>发送记录数统计结束{}", result);
        return result;
    }

    @GetMapping(value = "/setEndTime")
    @ApiOperation("设置核对截止时间")
    public Result setEndTime(String batchCode, String endTime) throws Exception {
        LOG.info("=================>>>>设置核对截止时间开始");
        Result result = null;
        try {

            salaryEmailService.updateEndTime(batchCode, endTime);

            result = Result.buildSuccess();
        } catch (ServiceException se) {
            LOG.error("=============>>>>设置核对截止时间出错", se);
            result = Result.buildFail(se.getCodeDesc(), se.getErrorMsg());
        } catch (Exception e) {
            LOG.error("=============>>>>设置核对截止时间出错", e);
            result = Result.buildFail();
        }
        LOG.info("=================>>>>设置核对截止时间结束{}", result);
        return result;
    }

}
